package com.jarchie.htgl.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jarchie.htgl.utils.BackHandlerHelper;
import com.jarchie.htgl.utils.FragmentBackHandler;

/**
 * Created by Jarchie on 2017\12\7.
 * 定义Fragment的基类
 */

public abstract class BaseFragment extends Fragment implements FragmentBackHandler {
    public Context mContext;
    protected View mRootView;
    private boolean isViewCreated; //控件是否初始化完成
    private boolean isLoadDataCompleted; //数据是否已经加载完成

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getUserVisibleHint()) {
            isLoadDataCompleted = true;
            initData();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getLayoutId() != 0) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
        }
        initView(mRootView);
        isViewCreated = true;
        setListener();
        return mRootView;
    }

    //此方法描述的是： 获取布局
    protected abstract int getLayoutId();

    //此方法描述的是： 初始化界面
    protected abstract void initView(View rootView);

    //此方法描述的是： 初始化监听事件
    protected abstract void setListener();

    //此方法描述的是： 初始化数据
    protected abstract void initData();

    @SuppressWarnings("unchecked")
    public <T extends View> T obtainView(int resId) {
        return (T) mRootView.findViewById(resId);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isViewCreated && !isLoadDataCompleted) {
            isLoadDataCompleted = true;
            initData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            setUserVisibleHint(true);
        }
    }

    //不需要处理Fragment返回键的不用重写该方法
    @Override
    public boolean onBackPressed() {
        return BackHandlerHelper.handleBackPress(this);
    }

}
